package com.crishne.anwo.filter;

import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.crishne.anwo.model.Menu;

public class AccessPageNeedLoginFilter implements Filter{
	
	private FilterConfig config;
	
	public FilterConfig getConfig() {
		return config;
	}
	
	public void setConfig(FilterConfig config) {
		this.config = config;
	}
	
	@SuppressWarnings("unused")
	private static boolean isUrlContains(String url, String str) {
		Pattern p = Pattern.compile("\\b" + str + "\\b");   
		Matcher m = p.matcher(url);
		return m.find();
	}
	
	private static boolean isUrlEndWith(String url, String str) {
		Pattern p = Pattern.compile("\\b" + str);   
		Matcher m = p.matcher(url);
		return m.find();
	}
	
	@SuppressWarnings("unused")
	private static boolean isEquals(String url, String str) {
		Pattern p = Pattern.compile(str);   
		Matcher m = p.matcher(url);
		return m.find();
	}
	
	private boolean isUrlIgnorable(String contextPath, String url) {
		if(url.endsWith("/") && contextPath.equals(url.substring(0, url.length()-1))) return true;
		if(this.getConfig().getInitParameter("Ignorable") != null &&
				!"".equals(this.getConfig().getInitParameter("Ignorable"))){
			
			String ignorablePage = this.getConfig().getInitParameter("Ignorable");
			String[] ignorablePages = ignorablePage.split(",");
			for(int i = 0 ; i < ignorablePages.length; i++){
				if(ignorablePages[i].endsWith("*")){
					if(url.startsWith(contextPath+ignorablePages[i].substring(0, ignorablePages[i].length()-1))){
						return true;
					}
				}
				else if ( isUrlEndWith(url, contextPath+ignorablePages[i].trim()) ) {
					return true;
				}
			}
		}
		return false;
	}
	
	private boolean isUrlNeedLogin(String contextPath, String url) {
		if(url.endsWith("/") && contextPath.equals(url.substring(0, url.length()-1))) return false;
		if(this.getConfig().getInitParameter("NeedLogin") != null &&
				!"".equals(this.getConfig().getInitParameter("NeedLogin"))){
			
			String needLoginPage = this.getConfig().getInitParameter("NeedLogin");
			String[] needLoginPages = needLoginPage.split(",");
			for(int i = 0 ; i < needLoginPages.length; i++){
				if(needLoginPages[i].endsWith("*")){
					String checkPage = needLoginPages[i].trim();
					if(url.startsWith(contextPath+checkPage.substring(0, checkPage.length()-1))){
						return true;
					}
				}
				else if ( isUrlEndWith(url, needLoginPages[i].trim()) ) {
					return true;
				}
			}
		}
		return false;
	}

	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)arg0;
		HttpServletResponse response = (HttpServletResponse)arg1;
		String url = request.getRequestURI();
		// 获取base url
		String path = request.getContextPath();
		if ( null == path ) {
			path = "";
		}
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
		//没有标识忽略 且 标识必须登录
		if ( !isUrlIgnorable(path, url) && isUrlNeedLogin(path, url)) {
			if ( request.getSession().getAttribute("userid") == null || 
					"".equals((String)request.getSession().getAttribute("userid")) ) {
				String loginPage = this.getConfig().getInitParameter("login");
				if ( loginPage != null && !"".equals(loginPage) ) {
					response.sendRedirect(basePath + loginPage);
					return;
				}
				response.sendRedirect(basePath + "login.jsp");
			}
			else{
//				if(!url.endsWith(".do") && !url.endsWith("index.jsp") && !url.endsWith("index.do")){ //*.do的链接暂时不考虑
//					//根据用户id，判断访问的地址是否授权 
//					List<Menu> menuList = (List<Menu>)request.getSession().getAttribute("userMenu");
//					boolean accessFlag = false;
//					for(int i=0;i<menuList.size();i++){
//						if(menuList.get(i).getStMenuUrl() != null
//								&& !"".equals(menuList.get(i).getStMenuUrl()) 
//								&& url.contains(menuList.get(i).getStMenuUrl())){
//							accessFlag = true;
//							break;
//						}
//					}
//					
//					if(!accessFlag){
//						response.sendRedirect(basePath + "errorpage/noAuth.jsp");
//						return;
//					}
//				}
			}
		}
		
		//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		// 在线统计 by ZLX @ 20160331
		//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//		HttpSession session = request.getSession();
//		String sessionApp = (String)session.getAttribute("session_app");
//		if ( "fao".equals(sessionApp) ) {
//			FaoLoginUserManager.add(session);	// 统计在线人数
//		}
		//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		
		arg2.doFilter(arg0, arg1);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		this.setConfig(arg0);		
	}

	

}
